#include "./draw_task.h"
#include "../../driver/ice/parts.h"
#include "../../driver/ice/sensor.h"
#include "../../utils/progress.h"

namespace task {

using namespace driver;
using namespace utils;

void DrawTask::run() {

    for (;;) {
        switch (m_state) {
            case State::IDLE: do_idle(); break;
            case State::WORK: do_work(); break;
            case State::STOP: do_stop(); break;
            case State::TIMEOUT: do_stop(); break;
            case State::OPEN: do_open(); break;
        }
    }
}

void DrawTask::do_idle() {
    uint32_t cond_count = 0;

    for (;;) {
        if (!sensor->is_bucket_high()) {
            cond_count ++;
            if (cond_count >= 5) {
                m_state = State::WORK;
                break;
            }
        } else {
            cond_count = 0;
        }

        if (wait(1000)) {
            break;
        }
    }
}

void DrawTask::do_work() {
 
    Progress prog;

    parts->open_pump();
    for (;;) {
        if (sensor->is_bucket_high()) {
            m_state = State::IDLE;
            break;
        } 

        if (prog.is_after(DRAW_TIMEOUT)) {
            m_state = State::TIMEOUT;
            break;
        }

        if (wait(500)) {
            break;
        }
    }
    parts->close_pump();
}

void DrawTask::do_stop() {
    parts->close_pump();
    wait();
}

void DrawTask::do_open() {
    parts->open_pump();
    wait();
}


}
